package com.common.util.repay_plan;

import com.common.util.date.DateUtil;

import java.util.ArrayList;
import java.util.Date;

/**
 * @describe: 计算还款计划每期的还款时间
 */
class RepayDateUtil {

    enum PeriodsUnit {
        /**
         * 月
         */
        MONTH(1),
        /**
         * 季度
         */
        SEASON(3);
        int value;
        
        PeriodsUnit(int value) {
            this.value = value;
        }
    }

    /**
     * 按月还款固定还款日获取还款日
     * @param startTime     计息开始时间
     * @param loanDays      借款天数
     * @param fixedRepayDay 固定还款日
     * @param periodsUnit 期限单位
     * @return
     */
    protected static ArrayList<Date> getRepayDate(Date startTime, final int loanDays, final int fixedRepayDay,
                                                  final PeriodsUnit periodsUnit) {

        ArrayList<Date> repayDateList = new ArrayList();
        Date endTime = DateUtil.getEndTime(DateUtil.addDay(startTime, loanDays - 1));
        Date repayDate = DateUtil.getDayDate(new Date(), fixedRepayDay);
        do {
            repayDate = DateUtil.getEndTime(DateUtil.getDate(repayDate, periodsUnit.value, fixedRepayDay));
            if (repayDate.compareTo(endTime) == -1) {
                repayDateList.add(repayDate);
            } else {
                if (repayDateList.size() > 0) {
                    Date beforeDate = repayDateList.get(repayDateList.size() - 1);
                    boolean flag = DateUtil.sameMonth(beforeDate, endTime);
                    if (flag) {
                        repayDateList.set(repayDateList.size() - 1, endTime);
                    } else {
                        repayDateList.add(endTime);
                    }
                } else {
                    repayDateList.add(endTime);
                }
                break;
            }
        } while (true);
        return repayDateList;
    }

}
